package 滑动窗口;

public class 水果成篮 {
    public int totalFruit(int[] fruits) {
        int kind = 0;
        int [] hash = new int [fruits.length];
        int result = 0;
        for(int left = 0, right = 0 ; right < fruits.length ; right++ ){
            if(hash[fruits[right]] == 0){
                kind ++;
            }
            hash[fruits[right]]++;//进窗口
            while(kind>2){
                hash[fruits[left]]--;
                if( hash[fruits[left]] == 0){
                    kind--;
                }
                left++;
            }
            if(kind <= 2){
                result = Math.max(result,right-left+1);
            }
        }
        return result ;
    }
    public int End(int [] f){
        int n = f.length;
        int [] hash = new int [n+1]; //统计窗口中水果的种类

        int ret = 0;
        for(int left = 0,right = 0,kinds=0;right < n ;right++)
        {
            int in = f[right];
            if(hash[in] == 0) kinds++; // 维护水果种类
            hash[in]++; //进窗口

            while(kinds > 2){
                int out =f[left];
                hash[out] --; //出窗口
                if(hash[out] == 0) kinds--;
                left++;
            }
        //更新结果
            ret = Math.max(ret,right-left+1);
        }
    return ret;
    }
}
